<template>
  <div>
    <Row :gutter="20">
      <Col span="8">
        <Card :bordered="false">
          <p slot="title">新增缓存地址</p>
          <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
            <FormItem label="名称" prop="name">
              <Input v-model="formValidate.name" placeholder="Enter your name"></Input>
            </FormItem>
            <FormItem label="所属环境" prop="env">
              <Select v-model="formValidate.env" placeholder="Select your env">
                <Option value="dev">dev</Option>
                <Option value="test">test</Option>
              </Select>
            </FormItem>
            <FormItem label="地址" prop="address">
              <Input v-model="formValidate.address" placeholder="Enter your address"></Input>
            </FormItem>
            <FormItem label="端口" prop="port">
              <Input v-model="formValidate.port" placeholder="Enter your port"></Input>
            </FormItem>
            <FormItem>
              <Button type="success" @click="handleSubmit('formValidate')" style="margin-left: 12px">创建</Button>
              <Button type="warning" @click="handleReset('formValidate')" style="margin-left: 12px">取消</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
      <Col span="16">
        <Card :bordered="false">
          <p slot="title">缓存详情列表</p>
          <Table border :columns="columns1" :data="data1">
            <template slot-scope="{ row }" slot="name">
              <strong>{{ row.name }}</strong>
            </template>
            <template slot-scope="{ row, index }" slot="action">
              <Button type="primary" size="small" style="margin-right: 5px" @click="handConnect(index)">测试</Button>
              <Button type="warning" size="small" style="margin-right: 5px" @click="show(index)">查看</Button>
              <Button v-if="permission.redis_delete === '1'" type="error" size="small" @click="remove(index)">删除</Button>
            </template>
          </Table>
        </Card>
      </Col>
    </Row>
  </div>
</template>

<script>
import { addCache, cacheList, connectStatus, deleteCache } from '@/api/database'

  export default {
    data () {
      return {
        formValidate: {
          name: '',
          address: '',
          port: '',
          env: ''
        },
        ruleValidate: {
          name: [
            { required: true, message: 'The name cannot be empty', trigger: 'blur' }
          ],
          env: [
            { required: true, message: 'Please select the env', trigger: 'change' }
          ],
          address: [
            { required: true, message: 'The address cannot be empty', trigger: 'blur' }
          ],
          port: [
            { required: true, message: 'The port cannot be empty', trigger: 'blur', }
          ]
        },
        columns1: [
          {
            title: '名称',
            key: 'name'
          },
          {
            title: '环境',
            key: 'env'
          },
          {
            title: '端口',
            key: 'port'
          },
          {
            title: '地址',
            key: 'address'
          },
          {
            title: '创建日期',
            key: 'create_time'
          },
          {
            title: '操作',
            slot: 'action',
            width: 200,
            align: 'center'
          }
        ],
        data1: [],
        permission: '',
      }
    },
    created () {
      this.data_list();
      this.get_permission();
    },
    methods: {
      // 获取用户操作权限
      get_permission () {
        const auth = JSON.parse(sessionStorage.getItem('permission'))
        this.permission = auth.child
      },
      // 获取缓存数据
      data_list () {
        cacheList().then(res => {
          this.data1 = res.data.results
        });
      },
      handleSubmit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            // 请求后端接口创建数据
            if ( this.permission.redis_create === '1') {
              addCache(this.formValidate).then(res => {
                this.data_list()  //在创建新地址时再次请求数据
                this.$Message.success({content:'创建成功!',duration: 5,closable: true});
              }).catch( err => {
                this.$Message.error({content:'创建失败!',duration: 5,closable: true})
              })
            } else {
              this.$Message.warning("权限不足！")
            }
          }
        })
      },
      handleReset (name) {
        this.$refs[name].resetFields();
      },
      // 显示信息
      show (index) {
        this.$Modal.info({
          title: '查看信息',
          content: `名称：${this.data1[index].name}<br>环境：${this.data1[index].env}<br>端口：${this.data1[index].port}<br>地址：${this.data1[index].address}<br>创建日期：${this.data1[index].create_time}`
        })
      },
      // 测试连接状态
      handConnect (index) {
        connectStatus(this.data1[index].id).then(res => {
          this.$Message.success({content:'连接成功!',duration: 5,closable: true})
        }).catch( err => {
          this.$Message.error({content:'无法连接!',duration: 5,closable: true})
        })
      },
      // 删除
      remove (index) {
        this.$Modal.confirm({
          title: "警告!",
          content: `<p>确认删除缓存${this.data1[index].name}地址？</p>`,
          onOk: () => {
            deleteCache(this.data1[index].id).then(res => {
              this.data1.splice(index, 1);
              this.$Message.success({content:'删除成功!',duration: 5,closable: true})
            }).catch(err => {
              this.$Message.error({content:'删除失败!',duration: 5,closable: true})
            })
            },
          onCancel: () => {
            this.$Message.info('已取消删除');
          }
        })
      }
    }
  }
</script>